package com.penjin.android.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.penjin.android.R;


/**
 * Created by Administrator on 2016/4/18.
 */
public class GetCodeView extends RelativeLayout {
    int count = 60;
    int nowCount;
    Handler handler;
    TextView text;
    public boolean isRunning = false;

    public GetCodeView(Context context) {
        super(context);
        init(context, null);
    }

    public GetCodeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public GetCodeView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attributeSet) {
        LayoutInflater.from(context).inflate(R.layout.widget_getcode, this);
        text = (TextView) findViewById(R.id.text);
        if (attributeSet != null) {
            TypedArray typedArray = null;
            try {
                typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.GetCodeView);
                count = typedArray.getInt(R.styleable.GetCodeView_getcode_count, 60);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (typedArray != null) {
                    typedArray.recycle();
                }
            }
        }
        handler = new Handler(context.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (nowCount > 0) {
                    text.setText(nowCount + "秒");
                    nowCount--;
                    handler.sendEmptyMessageDelayed(1, 1000);
                } else if (nowCount == 0) {
                    isRunning = false;
                }
            }
        };
    }

    public void start() {
        if (!isRunning) {
            this.nowCount = count;
            isRunning = true;
            handler.sendEmptyMessage(1);
        }
    }
}
